package org.hilo.boot.core.value;

import java.lang.reflect.Field;

import javax.persistence.Id;

import org.hilo.boot.core.UT;
import org.jretty.id.IdGenerator;
import org.jretty.id.Sequence;

/**
 * parse the Id annotation
 * 
 * @author zollty
 * @since 2018-03-20
 */
public class GerneratorIdInit implements FieldInitValue {
    
    private static IdGenerator idGenerator = new Sequence(); 

    @Override
    public boolean initField(Field field, Object standardBean, int type) {
        Id gid = field.getAnnotation(Id.class);
        if (gid != null && type == ActionType.ADD) {

            UT.Ref.makeAccessible(field);

            Object val = UT.Ref.getField(field, standardBean);
            if (val != null) {
                return false;
            }

            return initIdField(field, standardBean);
        }
        return false;
    }
    
    public static boolean initIdField(Field field, Object standardBean) {
        boolean ret = true;
        Class<?> type = field.getType();
        if (type.equals(Long.class)) {
            UT.Ref.setField(field, standardBean, idGenerator.nextId());
        } else if (type.equals(String.class)) {
            UT.Ref.setField(field, standardBean, String.valueOf(idGenerator.nextId()));
        } else {
            ret = false;
        }
        return ret;
    }

}
